package com.zs.handler;

import com.zs.http.Request;
import com.zs.http.Response;
import com.zs.server.TomcatServer;
import com.zs.servlet.Myservlet;

import java.io.*;
import java.net.Socket;

public class ServerHandler implements Runnable{

    //当前连接
    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }
    //run方法实现处理逻辑
    public void run() {
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            while (bufferedReader.readLine() != null) {
                if (bufferedReader.readLine().length() == 0) {
                    break;
                }
                System.out.println(bufferedReader.readLine());
            }
            OutputStream outputStream = socket.getOutputStream();
            Request request = new Request(inputStream);
            Response response = new Response(outputStream);
            System.out.println("开始执行客户请求，客户地址为：" + socket.getRemoteSocketAddress() + ",当前线程为：" + Thread.currentThread().getName());
            //通过请求的url获取setvlet实例
            String uri = request.getUri();
            String servlrtName = TomcatServer.uriMap.get(uri);
            if (servlrtName == "" || servlrtName == null) {
                String res = Response.responsebody + "can not find servlet";
                outputStream.write(res.getBytes());
                outputStream.close();
                inputStream.close();
            } else {
                Myservlet myservlet = TomcatServer.servletMap.get(servlrtName);
                myservlet.service(request,response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
